/*
 * @lc app=leetcode.cn id=149 lang=typescript
 *
 * [149] 直线上最多的点数
 */

// @lc code=start
function maxPoints(points: number[][]): number {
  if (points.length === 1) return 1;

  points.sort((a, b) => {
    if (a[0] !== b[0]) return a[0] - b[0];
    return a[1] - b[1];
  });

  const hash: Map<string, number> = new Map();
  const m = (x1: number, y1: number, x2: number, y2: number): { t: number; c: number } => {
    // 数学公式
    let t = (y2 - y1) / (x2 - x1);
    let c = (x2 * y1 - x1 * y2) / (x2 - x1);

    return { t, c };
  };

  for (let i = 0; i < points.length; i++) {
    let [x1, y1] = points[i];
    for (let j = i + 1; j < points.length; j++) {
      let [x2, y2] = points[j];
      let { t, c } = m(x1, y1, x2, y2);
      const key = `${x1}:${y1}:${t}:${c}`;
      hash.set(key, (hash.get(key) || 1) + 1);
    }
  }

  return Math.max(...hash.values());
}
// @lc code=end
